<script setup>
import {ref, onBeforeUnmount, nextTick} from 'vue';
import { message } from 'ant-design-vue';
import Pubsub from "pubsub-js";
import {uploadFile} from "@/api/UploadRequest.js";

const emit = defineEmits(['get-instance']);
const props = defineProps({
  option: {
    type: Object,
    required: true,
  },
});

const fileList = ref([]);
let md5LoadingPercent = ref(0);
let uploadBlobPercent = ref(0);

const md5Loading = Pubsub.subscribe('loading-md5', (msg, data) => {
  md5LoadingPercent.value = Math.floor(data.current/data.total * 100);
});
const uploadBlob = Pubsub.subscribe('upload-blob', (msg, data) => {
  uploadBlobPercent.value = Math.floor(data.current/data.total * 100);
  fileList.value[0].percent = uploadBlobPercent.value;
  if(data.current === data.total){
    fileList.value[0].status = 'done';
  }
});

const progress = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068',
  },
  strokeWidth: 3,
  format: percent => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test',
};

const handleChange = info => {
  console.log('info', info);
  // fileList.value = []
  // if(props.option.fileType !== undefined && props.option.fileType !== '') {
  //   if (info.file.type === props.option.fileType) {
  //     fileList.value.push(info.file);
  //   }
  // } else {
  //   fileList.value.push(info.file);
  // }

  const status = info.file.status;
  if (status !== 'uploading') {
    console.log('加载中',info.file, info.fileList);
  }
  if (status === 'done') {
    message.success(`${info.file.name} file uploaded successfully.`);
  } else if (status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};
function handleDrop(e) {
  console.log('Drop', e);
}

function beforeUpload(file) {
  if(props.option.fileType !== undefined && props.option.fileType !== ''){
    const isCorrectType = file.type === props.option.fileType;
    if (!isCorrectType) {
      message.error(`必须上传${props.option.fileType}类型的文件`);
      emit('get-instance', {
        err: `必须上传${props.option.fileType}类型的文件`
      });
    }
    return isCorrectType;
  }
}

async function handleUpload(data) {
  console.log('处理',data);
  const res = await uploadFile(data.file);
  if(res.code === 0 || res.code === 1){
    if (res.code === 1) {
      fileList.value[0].percent = 100;
      fileList.value[0].status = 'done';
    }
    await nextTick(() => {
      emit('get-instance', {
        success: true,
        md5: res.data.md5,
        bucketName: res.data.bucketName,
        objectName: res.data.objectName,
        file: data.file,
      });
    })
  } else {
    message.error(res.msg);
  }
}

function remove (file) {
  console.log('remove', file);
  emit('get-instance', {
    remove: true,
  });
  return true;
}

onBeforeUnmount(_=>{
  Pubsub.unsubscribe(md5Loading);
  Pubsub.unsubscribe(uploadBlob);
})
</script>

<template>
  <div style="max-width: 500px; background-color: #aaaaaa; min-height: 70px; text-align: center">
    <a-upload-dragger
        v-model:fileList="fileList"
        name="file"
        :multiple="false"
        :before-upload="beforeUpload"
        :customRequest="handleUpload"
        :progress="progress"
        @change="handleChange"
        @remove="remove"
        @drop="handleDrop"
    >
      <p class="ant-upload-drag-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="38" height="38" fill="currentColor" class="bi bi-cloud-upload-fill" viewBox="0 0 16 16">
          <path fill-rule="evenodd" d="M8 0a5.53 5.53 0 0 0-3.594 1.342c-.766.66-1.321 1.52-1.464 2.383C1.266 4.095 0 5.555 0 7.318 0 9.366 1.708 11 3.781 11H7.5V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11h4.188C14.502 11 16 9.57 16 7.773c0-1.636-1.242-2.969-2.834-3.194C12.923 1.999 10.69 0 8 0zm-.5 14.5V11h1v3.5a.5.5 0 0 1-1 0z"/>
        </svg>
      </p>
      <h2 style="color: antiquewhite;">
        {{props.option.areaTitle}}
      </h2>
    </a-upload-dragger>
    <a-progress
        style="margin-top: 10px"
        v-if="md5LoadingPercent > 0 && md5LoadingPercent<100"
        :stroke-color="{
        '0%': '#108ee9',
        '100%': '#87d068',
      }"
        :percent="md5LoadingPercent"
    />
  </div>
</template>

<style scoped>

</style>